<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>
    
    ES8 async和await - DSRBLOG
    
  </title>
  

  
  
  <link href="atom.xml" rel="alternate" title="DSRBLOG" type="application/atom+xml">
  <link rel="stylesheet" href="asset/css/style.min.css">
  <link rel="stylesheet" href="asset/css/doc.css">
  <script src="asset/app.js"></script>


</head>

<body> <section class="ct-body">
	<div class="container">
		<div class="columns is-variable bd-klmn-columns is-4 is-centered">
			<div class="column is-four-fifths">
				<div class="post-body single-content">
					
					<h1 class="title">
						ES8 async和await
					</h1>


					<div class="media">
						
						
						<div class="media-content">
							<div class="content">
								<p>
									<span class="date">2022/10/22 21:24 下午</span>
									

									

									<br />
									<span class="tran-tags">Tags:</span>&nbsp;
									
									<a class="tag is-link is-light">#ES7-11</a>
									

								</p>
							</div>
						</div>

					</div>
				</div>
				<article class="markdown-body single-content">
					<p><code>async</code>和<code>await</code>两种语法结合可以让异步代码像同步代码一样运行</p>
<h2><a id="async%E5%87%BD%E6%95%B0" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>async函数</h2>
<p>用于声明一种特殊的<code>async</code>函数</p>
<ol>
<li><code>async</code>函数的返回值一定是<code>promise</code>对象</li>
<li>若<code>return</code>返回的<strong>不是</strong><code>promise</code>对象，则返回结果为成功的<code>promise</code>对象</li>
</ol>
<pre class="line-numbers"><code class="language-js">async function fn() {
    return 'async函数';
}

const result = fn();
console.log(result);
//输出：Promise {status: &quot;resolved&quot;, result: &quot;async函数&quot;}
</code></pre>
<ol start="3">
<li>若抛出<strong>错误</strong>，则返回结果为失败的<code>promise</code>对象</li>
</ol>
<pre class="line-numbers"><code class="language-js">async function fn() {
    throw new Error('出错');
}

const result = fn();
console.log(result);
//输出：Promise {status: &quot;rejected&quot;, result: Error: 出错}
</code></pre>
<ol start="4">
<li>若<code>return</code>返回的是<code>promise</code>对象，则返回结果就是该<code>promise</code>对象</li>
</ol>
<pre class="line-numbers"><code class="language-js">async function fn() {
    return new Promise((resolve, reject) =&gt; {
        resolve('成功')
    })
}

const result = fn();
console.log(result);
//输出：Promise {status: &quot;resolved&quot;, result: &quot;成功&quot;}
</code></pre>
<h3><a id="%E8%B0%83%E7%94%A8then%E6%96%B9%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>调用then方法</h3>
<p>调用<code>then</code>的方式与<code>Promise</code>一样</p>
<pre class="line-numbers"><code class="language-js">result.then(value=&gt;{
    console.log(value);
},reason=&gt;{
    console.warn(reason);
})
</code></pre>
<h2><a id="await%E8%A1%A8%E8%BE%BE%E5%BC%8F" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>await表达式</h2>
<ol>
<li><code>await</code>必须写在<code>async</code>函数中</li>
<li><code>await</code>右侧的表达式一般为<code>promise</code>对象</li>
<li><code>await</code>返回的是<code>promise</code>成功的值</li>
<li><code>await</code>的<code>promise</code>失败了，会抛出异常，需要通过<code>try...catch</code>捕获处理</li>
</ol>
<pre class="line-numbers"><code class="language-js">//创建Promise对象
const p = new Promise((resolve,reject)=&gt;{
    resolve(&quot;成功&quot;);
})

//创建async函数
async function main() {
    try{
        //promise成功
        let result = await p;
        console.log(result);
    }catch(e){
        //promise失败
        console.log(e);
    }
}
</code></pre>
<h2><a id="async%E5%92%8Cawait%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>async和await结合使用</h2>
<h3><a id="%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>读取文件</h3>
<pre class="line-numbers"><code class="language-js">//引入fs模块
const fs = require('fs');

//读取第一个文件
function read01() {
    return new Promise((resolve, reject) =&gt; {
        fs.readFile(&quot;./resources/fs01.md&quot;, (err, data) =&gt; {
            if (err) reject(err);
            resolve(data);
        })
    })
}

//读取第二个文件
function read02() {
    return new Promise((resolve, reject) =&gt; {
        fs.readFile(&quot;./resources/fs02.md&quot;, (err, data) =&gt; {
            if (err) reject(err);
            resolve(data);
        })
    })
}

//声明async函数
async function main() {
    let r1 = await read01();
    let r2 = await read02();
    console.log(r1.toString());
    console.log(r2.toString());
}

main();
</code></pre>
<h3><a id="%E5%8F%91%E9%80%81ajax%E8%AF%B7%E6%B1%82" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>发送AJAX请求</h3>
<h4><a id="%E5%B0%81%E8%A3%85ajax%E8%AF%B7%E6%B1%82" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>封装AJAX请求</h4>
<pre class="line-numbers"><code class="language-js">function sendAJAX(url) {
    return new Promise((resolve, reject) =&gt; {
        //创建对象
        const x = new XMLHttpRequest();

        //初始化
        x.open('GET', url);

        //发送请求
        x.send();

        //事件绑定
        x.onreadystatechange = function () {
            if (x.readyState === 4) {
                if (x.status &gt;= 200 &amp;&amp; x.status &lt; 300) {
                    resolve(x.response);
                } else {
                    reject(x.status);
                }
            }
        }
    })
}
</code></pre>
<h4><a id="%E4%BD%BF%E7%94%A8promise%E6%96%B9%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>使用Promise方法</h4>
<p>使用<code>promise</code>一次只能发送一个<code>AJAX</code>请求</p>
<pre class="line-numbers"><code class="language-js">const result = sendAJAX(&quot;http://localhost:8080/getTest&quot;).then(value =&gt; {
    console.log(value);
}, reason =&gt; {
    console.warn(reason);
})
</code></pre>
<h4><a id="%E4%BD%BF%E7%94%A8async%E4%B8%8Eawait" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>使用async与await</h4>
<p>使用<code>async</code>和<code>await</code>可以非常简单的发送多个<code>AJAX</code>请求</p>
<pre class="line-numbers"><code class="language-js">async function main(){
    let result01 = await sendAJAX(&quot;http://localhost:8080/getTest&quot;);
    let result02 = await sendAJAX(&quot;http://localhost:8080/getTest&quot;);
    
    console.log(result01);
    console.log(result02);
}

main();
</code></pre>

				</article>
				<div class="comments-wrap">
					<div class="share-comments">
						

						

						
					</div>
				</div><!-- end comments wrap -->
			</div>
		</div><!-- end columns -->
	</div><!-- end container -->
</section>  














<script src="asset/prism.js"></script>









</body>

</html>